package com.codeerror.demo.view;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.codeerror.demo.R;
import com.codeerror.demo.bean.AnniversaryBean;
import com.codeerror.demo.bean.CardBean;
import com.codeerror.demo.bean.CountDownBean;
import com.codeerror.demo.bean.PromiseBean;
import com.codeerror.demo.bean.TodoListBean;
import com.codeerror.demo.util.DateUtil;

import java.util.Objects;

/**
 * 首页点击右下角添加按钮弹出的Dialog
 * 可添加的功能有：待办集，倒计时，纪念日，保证（承诺）......
 */
public class ShowAddDialog extends Dialog {
    public ShowAddDialog(@NonNull Context context) {
        super(context);
    }

    public static class Builder {
        private enum ADD_TYPE {
            SHOW_SELECTION,
            TODO_LIST,
            COUNT_DOWN,
            ANNIVERSARY,
            PROMISE,
        }

        private ShowAddDialog dialog;
        private View layout;
        private LinearLayout llShowSelection, llAddTodoList, llAddCountDown,
                llAddAnniversary, llAddPromise, llShowDetail, llSelectDate;
        private EditText et;
        private Button btnCreate;
        private TextView tvDate, tvInfo, tvBtnDate;
        private ImageView ivBack;

        private OnAddDialogDismissListener onAddDialogDismissListener;
        private OnCreateSuccessListener onCreateSuccessListener;

        private int curAddType = ADD_TYPE.SHOW_SELECTION.ordinal();
        private long curTime, startTime, endTime;

        public Builder(Context context) {
            dialog = new ShowAddDialog(context);
            layout = LayoutInflater.from(context)
                    .inflate(R.layout.layout_dialog_show_add, null, false);
            llShowSelection = layout.findViewById(R.id.ll_show_add_selection);
            llAddTodoList = layout.findViewById(R.id.ll_add_new_todo_list);
            llAddCountDown = layout.findViewById(R.id.ll_add_new_count_down);
            llAddAnniversary = layout.findViewById(R.id.ll_add_new_anniversary);
            llAddPromise = layout.findViewById(R.id.ll_add_new_promise);
            llShowDetail = layout.findViewById(R.id.ll_show_add_detail);
            et = layout.findViewById(R.id.et_dialog_add);
            tvDate = layout.findViewById(R.id.tv_add_dialog_selected_date);
            tvInfo = layout.findViewById(R.id.tv_show_add_info);
            ivBack = layout.findViewById(R.id.iv_dialog_add_back);
            btnCreate = layout.findViewById(R.id.btn_add_dialog_create);
            llSelectDate = layout.findViewById(R.id.ll_add_dialog_add_date);
            tvBtnDate = layout.findViewById(R.id.tv_add_dialog_add_date);

            curTime = startTime = System.currentTimeMillis();
            tvDate.setText("当前所选时间:\n" + DateUtil.getFormattedTime(curTime));
        }

        public Builder setOnAddDialogDismissListener(OnAddDialogDismissListener onAddDialogDismissListener) {
            this.onAddDialogDismissListener = onAddDialogDismissListener;
            return this;
        }

        public Builder setOnCreateSuccessListener(OnCreateSuccessListener onCreateSuccessListener) {
            this.onCreateSuccessListener = onCreateSuccessListener;
            return this;
        }

        public ShowAddDialog create() {
            dialog.setContentView(layout);
            dialog.setOnDismissListener(dialogInterface -> {
                onAddDialogDismissListener.onDismiss();
                dialog.dismiss();
            });

            llShowDetail.setVisibility(View.GONE);
            llAddTodoList.setOnClickListener(view -> {
                curAddType = ADD_TYPE.TODO_LIST.ordinal();
                updateAddType();
            });
            llAddCountDown.setOnClickListener(view -> {
                curAddType = ADD_TYPE.COUNT_DOWN.ordinal();
                updateAddType();
            });
            llAddAnniversary.setOnClickListener(view -> {
                curAddType = ADD_TYPE.ANNIVERSARY.ordinal();
                updateAddType();
            });
            llAddPromise.setOnClickListener(view -> {
                curAddType = ADD_TYPE.PROMISE.ordinal();
                updateAddType();
            });
            ivBack.setOnClickListener(view -> {
                curAddType = ADD_TYPE.SHOW_SELECTION.ordinal();
                curTime = startTime = System.currentTimeMillis();
                updateAddType();
            });

            llSelectDate.setOnClickListener(view -> {
                // 选择一个时间
                new SelectDateDialog.Builder(dialog.getContext())
                        .setCurTime(curTime)
                        .setOnSelectDateListener(millis -> {
                            curTime = millis;
                            tvDate.setText("当前所选时间:\n" + DateUtil.getFormattedTime(curTime));
                        }).create().showDialog();
            });

            btnCreate.setOnClickListener(view -> {
                if (TextUtils.isEmpty(et.getText().toString())) {
                    new PinkToast.Builder(dialog.getContext()).setText("输入不能为空哦").showToast();
                    return;
                }
                if (curAddType == ADD_TYPE.COUNT_DOWN.ordinal()) {
                    CardBean bean = new CountDownBean(et.getText().toString(), curTime);
                    bean.save();
                    onCreateSuccessListener.onSuccessCreate(bean);
                } else if (curAddType == ADD_TYPE.PROMISE.ordinal()) {
                    CardBean bean = new PromiseBean(et.getText().toString());
                    bean.save();
                    onCreateSuccessListener.onSuccessCreate(bean);
                }else if (curAddType == ADD_TYPE.ANNIVERSARY.ordinal()){
                    CardBean bean = new AnniversaryBean(et.getText().toString(), curTime);
                    bean.save();
                    onCreateSuccessListener.onSuccessCreate(bean);
                }else if (curAddType == ADD_TYPE.TODO_LIST.ordinal()){
                    CardBean bean = new TodoListBean(et.getText().toString(), curTime);
                    bean.save();
                    onCreateSuccessListener.onSuccessCreate(bean);
                }
                new PinkToast.Builder(dialog.getContext()).setText("创建成功").showToast();
                dialog.dismiss();
            });

            return dialog;
        }

        /**
         * 根据curAddType更新Dialog内容
         */
        private void updateAddType() {
            // 从选择界面切换到详情界面时
            if (curAddType != ADD_TYPE.SHOW_SELECTION.ordinal()) {
                // 设置返回按钮可见
                ivBack.setVisibility(View.VISIBLE);
                llSelectDate.setVisibility(View.VISIBLE);
                tvDate.setVisibility(View.VISIBLE);
                // 开启转换动画
                changeAnim(false);
                dialog.setCanceledOnTouchOutside(false);

                if (curAddType == ADD_TYPE.TODO_LIST.ordinal()) {
                    // 切换到添加待办集界面
                    tvBtnDate.setText("添加待办集的开始时间");
                    tvInfo.setText("添加一个待办集");
                    et.setHint("输入待办集的名称");
                } else if (curAddType == ADD_TYPE.COUNT_DOWN.ordinal()) {
                    // 切换到添加倒计时界面
                    tvBtnDate.setText("添加倒计时的截止时间");
                    tvInfo.setText("添加一个倒计时项目");
                    et.setHint("输入倒计时项目名称");
                } else if (curAddType == ADD_TYPE.ANNIVERSARY.ordinal()) {
                    // 切换到添加纪念日界面
                    tvBtnDate.setText("添加纪念日的日期");
                    tvInfo.setText("添加一个纪念日");
                    et.setHint("输入纪念日名称");
                } else if (curAddType == ADD_TYPE.PROMISE.ordinal()) {
                    // 切换到添加承诺界面
                    llSelectDate.setVisibility(View.GONE);
                    tvDate.setVisibility(View.GONE);
                    tvInfo.setText("添加一个承诺（决心）");
                    et.setHint("输入您承诺的事情");
                }
            } else {
                // 从详情界面返回选择界面
                // 设置返回按钮可见
                ivBack.setVisibility(View.GONE);
                // 开启转换动画
                changeAnim(true);
                dialog.setCanceledOnTouchOutside(true);
                tvInfo.setText("选择你要创建的项目");
            }
        }

        /**
         * 内容改变的动画
         *
         * @param isBackAnim 是否为返回动画
         */
        private void changeAnim(boolean isBackAnim) {
            ValueAnimator anim1 = ValueAnimator.ofFloat(1, 0);
            anim1.setDuration(300);
            anim1.start();
            anim1.addUpdateListener(valueAnimator -> {
                float val = (float) valueAnimator.getAnimatedValue();
                if (isBackAnim) {
                    llShowDetail.setAlpha(val);
                    llShowSelection.setVisibility(View.VISIBLE);
                    if (val == 1) {
                        llShowSelection.setAlpha(0);
                    }
                    llShowSelection.setAlpha(1 - val);
                    if (val == 0) {
                        llShowDetail.setVisibility(View.GONE);
                    }
                } else {
                    llShowSelection.setAlpha(val);
                    llShowDetail.setVisibility(View.VISIBLE);
                    if (val == 1) {
                        llShowSelection.setAlpha(0);
                    }
                    llShowDetail.setAlpha(1 - val);
                    if (val == 0) {
                        llShowSelection.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    /**
     * 展示Dialog，添加Dialog显示和消失的动画
     */
    public void showDialog() {
        Window window = getWindow();
        window.setBackgroundDrawableResource(R.color.transparent);
        // 缩放显示和消失
        window.setWindowAnimations(R.style.dialogWindowShowAnim);
        // 可按后退键退出，但不可点外边退出
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        show();
    }

    public interface OnAddDialogDismissListener {
        void onDismiss();
    }

    public interface OnCreateSuccessListener {
        void onSuccessCreate(CardBean cardBean);
    }

    @Override
    protected void onStart() {
        // 声明软键盘弹起时屏幕其他内容不需要跟着弹起
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onStart();
    }
}
